#include "app_functions.h"
#include "hardware.h"
#include "protocal.h"
#include "timer.h"


/************************************************************************************************************/
/************************************************************************************************************/
/************************************************************************************************************/
/*标志位操作和数值处理函数实现部分*/
/************************************************************************************************************/
/************************************************************************************************************/
/************************************************************************************************************/
/**
功能：标志位设置函数（针对所有标志位除了时间标志位）
返回：1-执行成功,0-执行失败
参数：flag-待操作的标志位
	  action-置1或置0
	  bit-操作标志位的第bit位
*/
uint8_t flag_operation(uint8_t* flag, uint8_t action, uint8_t bit_num)
{
	uint8_t state = 0;
	if (action == SET)
	{
		*flag |= bit_num;
		state = 1;
	}
	else if (action == CLEAR)
	{
		*flag &= ~(bit_num);
		state = 1;
	}
	return state;
}


/**
功能：读 标志位-位状态 函数（针对所有标志位除了时间标志位）
返回：标志位的位状态：1或0
参数：flag-待读的标志位
	  bit-操作标志位的第bit位
*/
uint8_t flag_read(const uint8_t* flag, uint8_t bit_num)
{
	uint8_t state = 0;
	if (((*flag) & (bit_num)) != 0)
	{
		state = 1;
	}
	return state;
}


/**
功能：最大差值计算功能函数
返回：数组里面最大值与最小值的差值
参数：data-数组
	  total-数据总数
*/
uint16_t sort(int16_t* dat, uint16_t total)
{
	uint16_t i, j;
	int16_t	value;
	if (dat != NULL && total > 0)
	{
		for (i = 0; i < total-1; i++)
		{
			for (j = i+1; j < total; j++)
			{
				if (dat[i] > dat[j])
				{
					value = dat[i];
					dat[i] = dat[j];
					dat[j] = value;
				}
			}
		}
		return (dat[total-1] - dat[0]);
	}
	else
	{
		return 0;
	}
}

/**
功能：计算热敏电阻对应温度功能函数
返回：温度，单位为摄氏度
参数：data-AD采样值
*/
float Calculate_Thermistor_Value(float dat)
{
	if (dat >= 13)		//-50开始算起
	{
		return (float)(1/(log((49.9 * ADC_BASE / dat - 49.9) * 1000 / 50000.0)/3950.0 + 1/(25.0+273.15))-273.15 + 0.5-2.5); //这里根据实验来考虑要不要修正
	}
	else
	{
		return -55.0;		//<20时标明未接传感器，返回-55摄氏度
	}
}

/**
功能：补偿AC电压值功能函数
返回：补偿后的AC电压值
参数：u16_AC_Voltage-AC原始值
	  u8_calib_value-标定值
*/
static uint16_t Offset_AC_Value(uint16_t u16_AC_Voltage, int8_t u8_calib_value)
{
	static int8_t calib = 0;
	
	if (u16_AC_Voltage <= 3)
	{
		calib = 0;
		u16_AC_Voltage -= u16_AC_Voltage;
	}
	else if (u16_AC_Voltage < 68)
	{
		calib = 0;
	}
	else if (u16_AC_Voltage > 68 && u16_AC_Voltage < 92)
	{
		calib = (u8_calib_value+2);
	}
	else if (u16_AC_Voltage > 92 && u16_AC_Voltage < 146)
	{
		calib = (u8_calib_value+3);
	}
	else if (u16_AC_Voltage > 146 && u16_AC_Voltage < 168)
	{
		calib = (u8_calib_value+4);
	}
	else if (u16_AC_Voltage > 168 && u16_AC_Voltage < 195)
	{
		calib = (u8_calib_value+5);
	}
	else if (u16_AC_Voltage > 195 && u16_AC_Voltage < 227)
	{
		calib = (u8_calib_value+6);
	}
	else if (u16_AC_Voltage > 227 && u16_AC_Voltage < 247)
	{
		calib = (u8_calib_value+7);
	}
	else if (u16_AC_Voltage > 247 && u16_AC_Voltage < 261)
	{
		calib = (u8_calib_value+8);
	}
	else if (u16_AC_Voltage > 261 && u16_AC_Voltage < 270)
	{
		calib = (u8_calib_value+9);
	}
	else if (u16_AC_Voltage > 270 && u16_AC_Voltage < 292)
	{
		calib = (u8_calib_value+10);
	}
	else if (u16_AC_Voltage > 292)
	{
		calib = (u8_calib_value+11);
	}

	u16_AC_Voltage += calib;
	
	return u16_AC_Voltage;		
}

uint16_t kalman_filter(uint16_t ADC_Value)
{
	float LastData;
	float NowData;
	float kalman_adc;
	static float kalman_adc_old = 130;	//默认100V
	static float P1;
	static float Q = 0.003;				//控制误差，结合目前10次滤波去一次值做计算的话取值0.003，越小响应速度越慢影响逻辑
	static float R = 10;				//测量误差，按照5σ取值10
	static float Kg = 0;
	static float P = 1;
	static uint8_t change_times = 0;

	/*NowData = ADC_Value;
	LastData = kalman_adc_old;
	P = P1 + Q;
	Kg = P / ( P + R );
	kalman_adc = LastData + Kg * ( NowData - kalman_adc_old );
	P1 = ( 1 - Kg ) * P;
	P = P1;
	kalman_adc_old = kalman_adc;*/

	NowData = ADC_Value;
	if (abs(kalman_adc_old-ADC_Value) >= 20)
	{
		change_times++;
		if (change_times >= 20)
		{
			change_times = 20;
			LastData = ADC_Value * 0.382 + kalman_adc_old * 0.618;
		}
		else
		{
			LastData = kalman_adc_old;
		}
	}
	else
	{
		if (change_times > 0)
		{
			change_times--;
		}
		LastData = kalman_adc_old;
	}
	
	P = P1 + Q;
	Kg = P / ( P + R );
	kalman_adc = LastData + Kg * ( NowData - kalman_adc_old );
	P1 = ( 1 - Kg ) * P;
	P = P1;
	kalman_adc_old = kalman_adc;
	
	return (uint16_t)(kalman_adc);
}

uint16_t kalman_filter_For_Iout(uint16_t ADC_Value)
{
	float LastData;
	float NowData;
	float kalman_adc;
	static float kalman_adc_old = 0;
	static float P1;
	static float Q = 0.001;			//控制误差，结合目前5次滤波取一次值做计算的话取值0.001，越小响应速度越慢
	static float R = 25;			//测量误差，按照5σ取值8
	static float Kg = 0;
	static float P = 1;

	static uint8_t change_times = 0;

	NowData = ADC_Value;
	if (abs(kalman_adc_old-ADC_Value) >= 30)
	{
		change_times++;
		if (change_times >= 20)
		{
			change_times = 20;
			LastData = ADC_Value * 0.382 + kalman_adc_old * 0.618;
		}
		else
		{
			LastData = kalman_adc_old;
		}
	}
	else
	{
		if (change_times > 0)
		{
			change_times--;
		}
		LastData = kalman_adc_old;
	}
	
	P = P1 + Q;
	Kg = P / ( P + R );
	kalman_adc = LastData + Kg * ( NowData - kalman_adc_old );
	P1 = ( 1 - Kg ) * P;
	P = P1;
	kalman_adc_old = kalman_adc;
	
	return (uint16_t)(kalman_adc);
}

uint16_t kalman_filter_For_Ich(uint16_t ADC_Value)
{
	float LastData;
	float NowData;
	float kalman_adc;
	static float kalman_adc_old = 0;
	static float P1;
	static float Q = 0.001;			//控制误差，结合目前5次滤波取一次值做计算的话取值0.005，越小响应速度越慢
	static float R = 120;			//测量误差，按照5σ取值20
	static float Kg = 0;
	static float P = 1;

	static uint8_t change_times = 0;

	NowData = ADC_Value;
	if (abs(kalman_adc_old-ADC_Value) >= 200)
	{
		change_times++;
		if (change_times >= 20)
		{
			change_times = 20;
			LastData = ADC_Value * 0.382 + kalman_adc_old * 0.618;
		}
		else
		{
			LastData = kalman_adc_old;
		}
	}
	else
	{
		if (change_times > 0)
		{
			change_times--;
		}
		LastData = kalman_adc_old;
	}
	
	P = P1 + Q;
	Kg = P / ( P + R );
	kalman_adc = LastData + Kg * ( NowData - kalman_adc_old );
	P1 = ( 1 - Kg ) * P;
	P = P1;
	kalman_adc_old = kalman_adc;
	
	return (uint16_t)(kalman_adc);
}

uint16_t kalman_filter_For_Temp(uint16_t ADC_Value)
{
	float LastData;
	float NowData;
	float kalman_adc;
	static float kalman_adc_old = 0;
	static float P1;
	static float Q = 0.001;		//控制误差，结合目前5次滤波取一次值做计算的话取值0.001，越小响应速度越慢
	static float R = 15;		//测量误差，按照5σ取值8
	static float Kg = 0;
	static float P = 1;

	static uint8_t change_times = 0;

	NowData = ADC_Value;
	if (abs(kalman_adc_old-ADC_Value) >= 30)
	{
		change_times++;
		if (change_times >= 20)
		{
			change_times = 20;
			LastData = ADC_Value * 0.382 + kalman_adc_old * 0.618;
		}
		else
		{
			LastData = kalman_adc_old;
		}
	}
	else
	{
		if (change_times > 0)
		{
			change_times--;
		}
		LastData = kalman_adc_old;
	}
	
	P = P1 + Q;
	Kg = P / ( P + R );
	kalman_adc = LastData + Kg * ( NowData - kalman_adc_old );
	P1 = ( 1 - Kg ) * P;
	P = P1;
	kalman_adc_old = kalman_adc;
	
	return (uint16_t)(kalman_adc);
}

static void Power_Output_State(const uint16_t Vout)
{	
	//输出处于(18,34)为正常	
	if ((Vout > LOAD_VOLTAGE_LOW_ALARM_RECOVERY) && (Vout < LOAD_VOLTAGE_OVER_ALARM_RECOVERY))				
	{
		flag_operation(&(gst_load.POWER_FLAG_OUTPUT_STATE), CLEAR, STATE);	
	}
	//	
	else if ((Vout > LOAD_VOLTAGE_OVER_ALARM) || (Vout < LOAD_VOLTAGE_LOW_ALARM))			
	{
		flag_operation(&(gst_load.POWER_FLAG_OUTPUT_STATE), SET, STATE);	
	}
}

/************************************************************************************************************/
/*传感器检测函数实现部分*/
/************************************************************************************************************/
/**
功能：Tiger电压检测,关机
返回：无
*/
void Check_Tiger_State(void)
{
	static uint8_t su8_Press_Time_Out = YES;

	if (gu8_detect_count == 0 && (gu16_detect_done & 0x0001))		//检测按键状态，每70ms一次
	{
		if (TIGER_IO_STATE() != LOW && su8_Press_Time_Out == NO) 	//检测到按键刚按下
	    {		 
			if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_MAINOFF) == SET 
				&& (IS_TIMER_STARTED(TIMER_TIGER_CUTOFF) == NO))	//只有AC不在时响应按键
			{
	    		SET_TIMER_MS(TIMER_TIGER_CUTOFF, TIMER_TIGER_CUTOFF_MS);  //定时3S
			}

			if (IS_TIMER_END(TIMER_TIGER_CUTOFF))					//定时完成后执行
		    {
				if (TIGER_IO_STATE() != LOW)						//持续3S
				{
					if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_MAINOFF) == SET)	//AC丢失
					{
			    		flag_operation(&(gu8_tiger_flag), SET, ACTION_BATOFF);	
					}
					su8_Press_Time_Out = YES;						//长按超过3S
				}
				else
				{
					flag_operation(&(gu8_tiger_flag), CLEAR, ACTION_BATOFF);
					su8_Press_Time_Out = NO;
				}
				CLEAR_TIMER(TIMER_TIGER_CUTOFF);	
		    }
	    } 
		else if(TIGER_IO_STATE() == LOW)							//按键松开，清空计时器，等待下次按下
		{	
			if (IS_TIMER_STARTED(TIMER_TIGER_CUTOFF) == YES)
			{
				CLEAR_TIMER(TIMER_TIGER_CUTOFF);
			}
			su8_Press_Time_Out = NO;
		}

		gu16_detect_done &= ~(0x0001);	
	}  
}



/**
功能：输出电压检测
返回：无
*/
void Check_VOUT_Voltage(void)
{	
	static uint16_t su16_load_voltage_ad_value = 0;
	static uint8_t k = 0;				

	if (gu8_detect_count == 0 && (gu16_detect_done & 0x0002))		//采样DEAL_WITH_CYCLE = 10次
	{	
		DISABLE_INTERRUPTS();
		su16_load_voltage_ad_value += getADC1(V_OUT);
		ENABLE_INTERRUPTS();
		k++;
		gu16_detect_done &= ~(0x0002);
		if (k >= DEAL_WITH_CYCLE)
		{				
			//扩大100倍，精度0.01V
			gst_load.voltage = (uint16_t)((su16_load_voltage_ad_value*1.0/(k) 
											* ADC_BASE_VOLTAGE * ADC_LOAD_OUTU_TIMES / ADC_BASE)*100 + 0.5);		
			su16_load_voltage_ad_value = 0;
			
			Power_Output_State(gst_load.voltage);
			
			k = 0;
			gu8_com_data_init_end 	|= 0x01;
			gu8_soft_wdg_clear_flag |= 0x01;
		}
	}	
}



/**
功能：AC交流电压检测
返回：无
*/
void Check_Acpower_Voltage(void)
{
	static uint8_t k = 0, su8_check_flag = 0, su8_detect_flag = 0;
	static uint16_t su16_ac_voltage_ad_value = 0;
	uint16_t ac_value_max = 0;
	uint8_t i;
	float v = 0;
	
	if (gu8_detect_count == 5 && (gu16_detect_done & 0x0004))	//等待DEAL_WITH_CYCLE = 10次
	{	
		if (su8_detect_flag == 0)
        {
            su8_detect_flag = 1;
            gu8_ac_detect_done = 0;
            TimerCap_Enable(); 
        }

		if (gu8_ac_detect_done == 1)							//上一次采样完成
        {
            ac_value_max = 0;
            for(i=0;i<ac_detect_count;i++)
            {
                if (ac_value_max < gu16_ac_ad_value[i])
                {
                    ac_value_max = gu16_ac_ad_value[i];
                }
            }
            su16_ac_voltage_ad_value = kalman_filter(ac_value_max);
			gst_acpower.ad_value = ac_value_max;
            k++;
			
			if (k < DEAL_WITH_CYCLE)
			{
				gu8_ac_detect_done = 0;
            	TimerCap_Enable(); 
			}

        }

		gu16_detect_done &= ~(0x0004);
		
		if (k >= DEAL_WITH_CYCLE)			//115us
		{
			v = (su16_ac_voltage_ad_value * 1.0 * ADC_BASE_VOLTAGE / ADC_BASE);
            v = v/510.0 * 117 * 1000;        
            v = v/1.414;
            gst_acpower.voltage = (uint16_t)(v*1.0 + 0.5);
			
			//补偿
			gst_acpower.voltage = Offset_AC_Value(gst_acpower.voltage, gs8_calib_ac_value);	
			
			//大于270V
			if (gst_acpower.voltage > ACPOWER_VOLTAGE_MAINOFF_OVER)						
			{
				if (su8_check_flag != 1)												//第一次切换到此状态，定时2S检测确认
				{
					SET_TIMER_MS(TIMER_CHECK_AC_VOLTAGE, TIMER_DELAY_2S); 
					su8_check_flag = 1;
				}
				
				if (IS_TIMER_END(TIMER_CHECK_AC_VOLTAGE))	
				{
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), SET, ACTION_MAINOFF|ACTION_CHARGEROFF);
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), CLEAR, STATE);
					flag_operation(&(gu8_output_power_flag), SET, STATE);				//指示备电
				}
			}
			//大于260V但小于270V
			else if (gst_acpower.voltage > ACPOWER_VOLTAGE_SIGNAL_OVER)					
			{
				if (su8_check_flag != 2)												//第一次切换到此状态，定时2S检测确认
				{
					SET_TIMER_MS(TIMER_CHECK_AC_VOLTAGE, TIMER_DELAY_2S); 
					su8_check_flag = 2;
				}
				
				if (IS_TIMER_END(TIMER_CHECK_AC_VOLTAGE))									
				{
					if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), ACTION_MAINOFF) == CLEAR)
					{
						flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), SET, STATE);
					}
				}
			}
			//小于255V
			else if (gst_acpower.voltage < ACPOWER_VOLTAGE_OVER_RECOVERY)				
			{
				if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), STATE|ACTION_MAINOFF|ACTION_CHARGEROFF) == SET)
				{
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_MAINOFF|ACTION_CHARGEROFF);
				}
			}

			//小于90V
			if (gst_acpower.voltage < ACPOWER_VOLTAGE_MAINOFF_LOW)						
			{
				if (su8_check_flag != 3)												//第一次切换到此状态，定时2S检测确认
				{
					SET_TIMER_MS(TIMER_CHECK_AC_VOLTAGE, TIMER_DELAY_2S); 
					su8_check_flag = 3;
				}
				
				if (IS_TIMER_END(TIMER_CHECK_AC_VOLTAGE))	
				{
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), SET, ACTION_MAINOFF|ACTION_CHARGEROFF);
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), CLEAR, STATE);
					flag_operation(&(gu8_output_power_flag), SET, STATE);				//指示备电
				}
			}
			//90-95V
			else if (gst_acpower.voltage < ACPOWER_VOLTAGE_SIGNAL_LOW)					
			{
				if (su8_check_flag != 4)												//第一次切换到此状态，定时2S检测确认
				{
					SET_TIMER_MS(TIMER_CHECK_AC_VOLTAGE, TIMER_DELAY_2S); 
					su8_check_flag = 4;
				}
				if (IS_TIMER_END(TIMER_CHECK_AC_VOLTAGE))	
				{
					if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_MAINOFF) == CLEAR)
					{
						flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), SET, STATE);
					}
				}
			}
			//大于100V
			else if (gst_acpower.voltage > ACPOWER_VOLTAGE_LOW_RECOVERY)				
			{
				if (flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), STATE|ACTION_MAINOFF|ACTION_CHARGEROFF) == SET)
				{
					flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), CLEAR, STATE|ACTION_MAINOFF|ACTION_CHARGEROFF);
				}
				if (flag_read(&(gu8_tiger_flag), ACTION_BATOFF) == SET)
				{
					//AC恢复正常，清除备电关机标志位，恢复主备电自动切换功能
					flag_operation(&(gu8_tiger_flag), CLEAR, ACTION_BATOFF);			
				}
			}
			//(100,255)
			if (gst_acpower.voltage > ACPOWER_VOLTAGE_LOW_RECOVERY && gst_acpower.voltage < ACPOWER_VOLTAGE_OVER_RECOVERY)
			{
				//正常区间
				su8_check_flag = 0;													
				CLEAR_TIMER(TIMER_CHECK_AC_VOLTAGE);
				flag_operation(&(gu8_output_power_flag), CLEAR, STATE);				//指示主电
			}

			k = 0;
			su8_detect_flag = 0;
			gu8_com_data_init_end 	|= 0x02;
			gu8_soft_wdg_clear_flag |= 0x02;
		}
	}
}



/**
功能：电池总压检测
返回：无
*/
void Check_Battery_Voltage(void)
{
	static uint8_t k = 0, vbat_over_count = 0;
	static uint16_t su16_bat_voltage_ad_value = 0;
	uint16_t temp = 0, Cbat_value = 0;
	
	if (gu8_detect_count == 1 && (gu16_detect_done & 0x0008))		//采样DEAL_WITH_CYCLE = 10次
	{
		DISABLE_INTERRUPTS();
		su16_bat_voltage_ad_value += getADC0(BAT);					//25-28us左右
		ENABLE_INTERRUPTS();
		
		k++;
		gu16_detect_done &= ~(0x0008);
		
		if (k >= DEAL_WITH_CYCLE)			//75us左右执行完
		{
			//扩大100倍，精度0.01V
			gst_battery.voltage = (uint16_t)(su16_bat_voltage_ad_value * 1.0 / (k) 
											* ADC_BASE_VOLTAGE / ADC_BASE * ADC_BAT_TIMES * 100  + 0.5);
			su16_bat_voltage_ad_value = 0;
			if (flag_read(&(gu8_output_power_flag), STATE) == MAIN_OUT) 
			{
				temp = gst_battery.voltage*10 - (gst_battery.chg_current*gst_battery.resistance/10); 
				
				if (temp > 24500)
				{
					Cbat_value = 40 + (temp-24500)/25;
				}
				else if (temp > 23500)
				{
					Cbat_value = (temp-23500)/25;
				}
				else 
				{
					Cbat_value = 0;
				}
			}
			else
			{
				temp = gst_battery.voltage*10 + (gst_load.current*gst_battery.resistance/10);  
				
				if (temp > 24000)
				{
					Cbat_value = 50 + (temp-24000)/40;
				}
				else if (temp > 21000)
				{
					Cbat_value = (temp-21000)/60;
				}
				else 
				{
					Cbat_value = 0;
				}
			}
			if (Cbat_value > 99)
			{	
				Cbat_value = 99;  //电池电量
			}
			if ((flag_read(&(gst_battery.BATTERY_FLAG_FULL), STATE) == SET) && (Cbat_value>80))
			{
				Cbat_value = 100;
			}
			Cbat_value = Cbat_value * 2; 
			gst_battery.capacity = Cbat_value;													//电池电量

			//备电没有丢失，否则清除并不再更新电池相关标志位
			if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
			{
				//铅酸电池
				if (gst_battery.voltage > BATTERY_VOLTAGE_LOW_RECOVERY)
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE), CLEAR, STATE);
				}	
				else if (gst_battery.voltage < BATTERY_VOLTAGE_SIGNAL_LOW)							//欠压点
				{
					if (flag_read(&(gst_charger.CHARGER_FLAG_STATUS), STATE) == SET)				//没有在充电
					{
						if (flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), STATE) == CLEAR)		//没有触发过放
						{
							flag_operation(&(gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE), SET, STATE);
						}
						else																		//触发过放,清除欠压标志位
						{
							flag_operation(&(gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE), CLEAR, STATE);
						}
					}
					//充电中，暂定清除欠压、过放等标志位
					else if (flag_read(&(gst_charger.CHARGER_FLAG_STATUS), STATE) == CLEAR)			
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE), CLEAR, STATE);
					}
				}
				
				if (gst_battery.voltage < BATTERY_VOLTAGE_BATOFF_LOW_LEAD_ACID)						//过放点
				{						
					if (flag_read(&(gst_charger.CHARGER_FLAG_STATUS), STATE) == SET)
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), SET, STATE|ACTION_BATOFF);
					}
					else if (flag_read(&(gst_charger.CHARGER_FLAG_STATUS), STATE) == CLEAR)
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), CLEAR, STATE);
					}
				}
				else if (gst_battery.voltage > BATTERY_VOLTAGE_BATOFF_LOW_LEAD_ACID)				//过放点恢复
				{	
					//处于主电模式
					if (flag_read(&(gu8_output_power_flag), STATE) == MAIN_OUT)						
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), CLEAR, STATE|ACTION_BATOFF);
					}
				}
	
				if (gst_battery.voltage < BATTERY_VOLTAGE_CHARGEROFF_LOW)
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), SET, ACTION_CHARGEROFF);
				}
				else if (gst_battery.voltage > BATTERY_VOLTAGE_CHARGEROFF_LOW_RECOVERY)
				{ 
					flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), CLEAR, ACTION_CHARGEROFF);
				}
				
				if (gst_battery.voltage > BATTERY_VOLTAGE_CHARGEROFF_OVER)
				{
					//检测到电池端口过压，尝试打开放电电路放电，目前只能通过充电电流解除
					if (gu8_get_real_vbat_flag == NO)
					{
						BAT_LOSS_D_ON();
						gu8_get_real_vbat_flag = YES;
					}	
					
					if (gu8_get_real_vbat_flag == YES)
					{
						vbat_over_count++;					
						if (vbat_over_count >= 3)		//检测到连续过压3次报警，此时放电回路应是打开的状态
						{
							vbat_over_count = 0;
							flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_OVER), SET, STATE|ACTION_CHARGEROFF);
						}
					}
				}
				else if (gst_battery.voltage < BATTERY_VOLTAGE_CHARGEROFF_OVER_RECOVERY)
				{
					vbat_over_count = 0;
					flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_CHARGEROFF);
				}
			}
			
			//充电端口短路可以和丢失标志一起报
			if (gst_battery.voltage <= BATTERY_VOLTAGE_PORT_SHORT && gu8_detect_bat_lost_flag == NO)				
			{
				flag_operation(&(gst_battery.BATTERY_FLAG_PORT_SHORT), SET, STATE|ACTION_CHARGEROFF);
			}
			else if (gst_battery.voltage > BATTERY_VOLTAGE_PORT_SHORT_RECOVERY)
			{
				flag_operation(&(gst_battery.BATTERY_FLAG_PORT_SHORT), CLEAR, STATE|ACTION_CHARGEROFF);
			}
			
			k = 0;
			gu8_com_data_init_end |= 0x04;
			gu8_soft_wdg_clear_flag |= 0x04;
		}
	}
}


/**
功能：电池中点电压检测
返回：无
*/
void Check_Bat_Middle_Dot_Voltage(void)
{
	static uint8_t k = 0;
	
	static uint16_t su16_bat_m1_voltage_ad_value = 0;
#if CHECK_BAT_3_CELL_EN > 0
	static uint16_t	su16_bat_m2_voltage_ad_value = 0;
#endif

	int16_t  s16_data[2];
	uint16_t u16_m1_voltage = 0;
	uint16_t u16_sv, u16_diff;

	if (gu8_detect_count == 1 && (gu16_detect_done & 0x0008) == 0 && (gu16_detect_done & 0x0010))	//采样DEAL_WITH_CYCLE = 10次
	{
		DISABLE_INTERRUPTS();
		su16_bat_m1_voltage_ad_value += getADC1(BAT_M1);
#if CHECK_BAT_3_CELL_EN > 0
		su16_bat_m2_voltage_ad_value += getADC1(BAT_M2);
#endif
		ENABLE_INTERRUPTS();
		k++;
		gu16_detect_done &= ~(0x0010);
		
		if (k >= DEAL_WITH_CYCLE)		//80us
		{
#if CHECK_BAT_3_CELL_EN > 0
			u16_m1_voltage = ((su16_bat_m1_voltage_ad_value > su16_bat_m2_voltage_ad_value) ? su16_bat_m1_voltage_ad_value : su16_bat_m2_voltage_ad_value);
#else
			u16_m1_voltage = su16_bat_m1_voltage_ad_value;
#endif
			//扩大100倍，精度0.01V
			gst_battery.m1_voltage = (uint16_t)(u16_m1_voltage * 1.0 / (k) 
									 			* ADC_BASE_VOLTAGE / ADC_BASE * ADC_BAT_MIDDLE_TIMES * 100 + 0.5);
			su16_bat_m1_voltage_ad_value = 0;
#if CHECK_BAT_3_CELL_EN > 0
			su16_bat_m2_voltage_ad_value = 0;
#endif

			if (gst_battery.voltage >= gst_battery.m1_voltage)
			{
				u16_sv = gst_battery.voltage - gst_battery.m1_voltage;
			}
			else
			{
				u16_sv = 0;
			}
			s16_data[0] = (int16_t)gst_battery.m1_voltage;
			s16_data[1] = (int16_t)u16_sv;
			
			u16_diff = sort(s16_data,2);		//处理之后s16_data[0]存放最小值，s16_data[1]存放最大值，u16_diff存放两者差值
			if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
			{
				//单节超过15.0V或是单节低于8.0V
				if (s16_data[1] > BATTERY_VOLTAGE_SINGLE_OVER || s16_data[0] < BATTERY_VOLTAGE_SINGLE_LOW)
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_SINGLE_VOLTAGE), SET, STATE);	//单节电压异常
				}
				//单节超过8.5V且低于14.5V
				else if (s16_data[1] < BATTERY_VOLTAGE_SINGLE_OVER_RECOVERY && s16_data[0] > BATTERY_VOLTAGE_SINGLE_LOW_RECOVERY)
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_SINGLE_VOLTAGE), CLEAR, STATE);
				}
		
				if (flag_read(&(gst_battery.BATTERY_FLAG_FULL), STATE) == SET)				//充满之后再检测
				{
					if (u16_diff > BATTERY_VOLTAGE_DIFFERENCE_OVER)							//电池间压差异常
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE), SET, STATE);
					}
					else if (u16_diff < BATTERY_VOLTAGE_DIFFERENCE_OVER_RECOVERY)
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE), CLEAR, STATE);
					}
				}
				else 
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE), CLEAR, STATE);
				}
			}
			k = 0;
			gu8_com_data_init_end |= 0x08;
			gu8_soft_wdg_clear_flag |= 0x08;
		}	
	}
}



/**
功能：充电电流检测
返回：无
*/
void Check_Charger_Current(void)
{
	static uint8_t k = 0, su8_stat_switch = BAT_OUT, su8_current_stat = 2;
	static uint16_t su16_det_lost_ad_value = 0;
	
	if (gu8_detect_count == 1 && (gu16_detect_done & 0x0020))		//采样DEAL_WITH_CYCLE = 10次
	{
		DISABLE_INTERRUPTS();
		su16_det_lost_ad_value = getADC0(I_CHARGER);
		ENABLE_INTERRUPTS();
		su16_det_lost_ad_value = kalman_filter_For_Ich(su16_det_lost_ad_value);
		k++;
		gu16_detect_done &= ~(0x0020);
		
		if (k >= DEAL_WITH_CYCLE)				//85us
		{
			//扩大100倍，精度0.01A
			gst_battery.chg_current = (uint16_t)(su16_det_lost_ad_value * 1.0 
									  			 * ADC_BASE_VOLTAGE / ADC_BASE / ADC_CHARGER_I_TIMES * 100 + 0.5);	


			if (gst_battery.chg_current >= 18)
			{
				gst_battery.chg_current += 7;
			}
			
			//主电状态下才判断充电电流状态
			if (flag_read(&(gu8_output_power_flag), STATE) == MAIN_OUT)						
			{
				su8_stat_switch = MAIN_OUT;													//指示主电输出
				if (gst_battery.chg_current < BATTERY_LOST_CHECK_CURRENT)					//充电电流小于 0.15A
				{
					if (su8_current_stat != 1)												//充电电流由大变小
					{
						su8_current_stat = 1;
						if (IS_TIMER_STARTED(TIMER_CHECK_BATTERY_LOST))
						{
							CLEAR_TIMER(TIMER_CHECK_BATTERY_LOST);
						}
					}
					//定时器空闲，电池不丢失的情况下，间隔300S检测一次丢失情况
					if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
					{
						if (IS_TIMER_STARTED(TIMER_CHECK_BATTERY_LOST) == NO)
						{
							SET_TIMER_MS(TIMER_CHECK_BATTERY_LOST, TIMER_CHECK_BATTERY_LOST_MS);	//定时300S
						}
					}
					//电池丢失的情况下，间隔1S检测一次丢失情况
					else	
					{
						if (IS_TIMER_STARTED(TIMER_CHECK_BATTERY_LOST) == NO)						//设定延时1s
						{
							SET_TIMER_MS(TIMER_CHECK_BATTERY_LOST, TIMER_CHECK_BATTERY_LOST_1S);	//定时1S
						}
					}
						
					if (IS_TIMER_END(TIMER_CHECK_BATTERY_LOST) == YES)								//电流持续300S 小于 BATTERY_LOST_CHECK_CURRENT
					{
						if (gu8_detect_bat_lost_flag == NO && gu8_detect_battery_resistance_flag == NO)
						{
							gu8_detect_bat_lost_flag = YES;
							CLEAR_TIMER(TIMER_CHECK_BATTERY_LOST);
						}
					}
				}
				//有充电电流
				else if (gst_battery.chg_current > BATTERY_CHARGING_RECOVERY_CURRENT_LEAD_ACID)
				{
					if (su8_current_stat != 0)												//充电电流由小变大
					{
						su8_current_stat = 0;
						SET_TIMER_MS(TIMER_CHECK_BATTERY_LOST, TIMER_VCH_DELAY_MS);			//定时3S
					}
					if (IS_TIMER_END(TIMER_CHECK_BATTERY_LOST) == YES)
					{
						flag_operation(&(gst_charger.CHARGER_FLAG_STATUS), CLEAR, STATE);	//充电中	
						//CLEAR_TIMER(TIMER_CHECK_BATTERY_LOST);
					}

					//发现有充电电流时，如果没有在处于内阻检测的过程，则关掉放电回路
					if (BAT_LOSS_IO_STATE() != LOW 
						&& (gu8_detect_bat_lost_flag == YES || gu8_get_real_vbat_flag == YES)
						&& gu8_detect_battery_resistance_flag == NO)
					{
						BAT_LOSS_D_OFF();
					}
					//有充电电流，目前不再去检测备电丢失和电池过压的情况了
					flag_operation(&(gst_battery.BATTERY_FLAG_LOST), CLEAR, STATE|ACTION_CHARGEROFF);		
					gu8_detect_bat_lost_flag = NO;	
					gu8_get_real_vbat_flag = NO;
				}
			}
			//备电状态
			else																	
			{
				//第一次从主电切换到备电，强制进行一次备电丢失检测
				if (su8_stat_switch != BAT_OUT)													
				{
					su8_stat_switch = BAT_OUT;
					
					if (IS_TIMER_STARTED(TIMER_CHECK_BATTERY_LOST))
					{
						CLEAR_TIMER(TIMER_CHECK_BATTERY_LOST);
					}
					if (gu8_get_real_vbat_flag == NO)
					{
						BAT_LOSS_D_OFF();
					}
					gu8_detect_bat_lost_flag = YES;
					gu8_get_real_vbat_flag = NO;
				}
			}
			k = 0;
			gu8_com_data_init_end |= 0x10;
			gu8_soft_wdg_clear_flag |= 0x10;
		}
	}
}



/**
功能：电池开路检测
返回：无
*/
void Check_Battery_Lost(void)
{
	uint16_t u16_det_lost_ad_value = 0;
	
	if (gu8_detect_bat_lost_flag == YES)												//备电丢失检测标志位置位
	{	
		if(IS_TIMER_STARTED(TIMER_CHECK_BATTERY_LOST) == NO)
		{
			//设定延时，该定时器和充电电流检测模块共用，但是在过程中不影响
			SET_TIMER_MS(TIMER_CHECK_BATTERY_LOST, 400);														
			flag_operation(&(gst_battery.BATTERY_FLAG_LOST), SET, ACTION_CHARGEROFF);	//先关闭充电器
			CHARGER_OFF();
			BAT_LOSS_D_ON();
		}
		if (IS_TIMER_END(TIMER_CHECK_BATTERY_LOST) == YES)								//延时时间到
		{
			CLEAR_TIMER(TIMER_CHECK_BATTERY_LOST);
			DISABLE_INTERRUPTS();
			u16_det_lost_ad_value = getADC0(BAT);
			ENABLE_INTERRUPTS();
			if (gu8_get_real_vbat_flag == NO)											//没有其他地方需要则关闭放电回路
			{
				BAT_LOSS_D_OFF();
			}
			gu8_detect_bat_lost_flag = NO;
			
			//电池存在, 恢复充电
			if (u16_det_lost_ad_value > THRESHOLD_V(15.0))								
			{
				//打开充电开关
				flag_operation(&(gst_battery.BATTERY_FLAG_LOST), CLEAR, STATE|ACTION_CHARGEROFF); 									
			}
			//电池已丢失  	，清除关于电池电压的异常标志位
			else if (u16_det_lost_ad_value < THRESHOLD_V(15.0))							
			{
				flag_operation(&(gst_battery.BATTERY_FLAG_LOST), SET, STATE|ACTION_CHARGEROFF);
				flag_operation(&(gst_battery.BATTERY_FLAG_FULL), CLEAR, STATE);
				flag_operation(&(gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE), CLEAR, STATE);
				flag_operation(&(gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE), CLEAR, STATE);
				flag_operation(&(gst_battery.BATTERY_FLAG_SINGLE_VOLTAGE), CLEAR, STATE);
				flag_operation(&(gst_battery.BATTERY_FLAG_BAT_OVER_TEMP), CLEAR, STATE|ACTION_CHARGEROFF);
				flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), CLEAR, STATE|ACTION_CHARGEROFF);
				flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_CHARGEROFF);
			}
		}		
	}
}


/**
功能：负载电流检测
返回：无
*/
void Check_Load_Current(void)
{
	static uint16_t su16_load_voltage = 0, su16_load_current_ad_value = 0;
	static uint8_t  su8_ad_count = 0, count_flag = 0, k = 0;

	if (gu8_detect_count == 2 && (gu16_detect_done & 0x0040))		//采样DEAL_WITH_CYCLE-5 = 5次
	{
		DISABLE_INTERRUPTS();
		su16_load_current_ad_value = getADC1(I_OUT);
		ENABLE_INTERRUPTS();
		su16_load_current_ad_value = kalman_filter_For_Iout(su16_load_current_ad_value);

		k++;
		gu16_detect_done &= ~(0x0040);
		if (k >= (DEAL_WITH_CYCLE-5))			//90us
		{
			//扩大100倍，精度0.01A
			gst_load.current = (uint16_t)(su16_load_current_ad_value * 1.0
							   * ADC_BASE_VOLTAGE / ADC_BASE / ADC_LOAD_OUTI_TIMES * 100 + 0.5); 

			if (gst_load.current > 350 && gst_load.current < 500)
			{
				gst_load.current -= 10;
			}
			else if (gst_load.current > 500 && gst_load.current < 700)
			{
				gst_load.current -= 20;
			}
			else if (gst_load.current > 700 && gst_load.current < 900)
			{
				gst_load.current -= 30;
			}
			else if (gst_load.current > 900)
			{
				gst_load.current -= 40;
			}
			
			if (gst_load.current > LOAD_CURRENT_OVER4)				//过流点4---40A，0.5S关机
			{
				if (count_flag != 4)								//第一次切换到此状态，定时0.5S检测确认
				{
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_OVER4_DELAY_MS);		//定时0.5S
					count_flag = 4;
				}
			    
				if (IS_TIMER_END(TIMER_LOAD_RECOVERY))				//持续0.5S
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_OVER), SET, STATE|ACTION_MAINOFF|ACTION_BATOFF);
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
					//定时10S恢复，但此项目因系统会掉电，具体恢复时间看系统掉电情况
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_RECOVERY_MS);			
				}
			}
			else if (gst_load.current > LOAD_CURRENT_OVER3)			//过流点3---30A
			{
				if (count_flag != 3)								//第一次切换到此状态，定时1S检测确认
				{
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_OVER3_DELAY_MS);		//定时1S
					count_flag = 3;
				}
				if (IS_TIMER_END(TIMER_LOAD_RECOVERY))				//持续1S
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_OVER), SET, STATE|ACTION_MAINOFF|ACTION_BATOFF);
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
					//定时10S恢复，但此项目因系统会掉电，具体恢复时间看系统掉电情况
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_RECOVERY_MS);			
				}
			}
			else if (gst_load.current > LOAD_CURRENT_OVER2)			//过流点2---20A
			{
				if (count_flag != 2)								//第一次切换到此状态，定时2S检测确认
				{
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_OVER2_DELAY_MS);		//定时2S
					count_flag = 2;
				}
				if (IS_TIMER_END(TIMER_LOAD_RECOVERY))				//持续2S
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_OVER), SET, STATE|ACTION_MAINOFF|ACTION_BATOFF);
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
					//定时10S恢复，但此项目因系统会掉电，具体恢复时间看系统掉电情况
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_RECOVERY_MS);			
				}
			}
			else if (gst_load.current > LOAD_CURRENT_OVER1)			//过流点1---9.1A
			{
				if (count_flag != 1)								//第一次切换到此状态，定时3S检测确认
				{
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_OVER1_DELAY_MS);		//定时3S
					count_flag = 1;
				}
				if (IS_TIMER_END(TIMER_LOAD_RECOVERY))				//持续3S
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_OVER), SET, STATE|ACTION_MAINOFF|ACTION_BATOFF);
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
					//定时10S恢复，但此项目因系统会掉电，具体恢复时间看系统掉电情况
					SET_TIMER_MS(TIMER_LOAD_RECOVERY, TIMER_LOAD_RECOVERY_MS);		
				}
			}
			else if (gst_load.current > LOAD_CURRENT_SIGNAL_OVER)		//过流报警点---8.4A-9.1A
			{
				//gst_load.flag = 1;
				if (flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), STATE) == CLEAR)
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), SET, STATE);
					CLEAR_TIMER(TIMER_LOAD_RECOVERY);
					count_flag = 0;
				}

			}
			else if (gst_load.current < LOAD_CURRENT_SIGNAL_RECOVERY)	//解除过流---7.5A
			{
				flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
				
				if (flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), STATE) == CLEAR
				    && IS_TIMER_STARTED(TIMER_LOAD_RECOVERY))
				{
					CLEAR_TIMER(TIMER_LOAD_RECOVERY);
					count_flag = 0;
				}
				   
				if (flag_read(&(gst_load.LOAD_FLAG_CURRENT_SHORT), ACTION_BATOFF) == SET)
	            {
	            	DISABLE_INTERRUPTS();
	                su16_load_voltage += getADC1(V_OUT);
					ENABLE_INTERRUPTS();
	                su8_ad_count++;
	                if (su8_ad_count >= 3)							//2S解除备电短路保护
	                {
	                    su16_load_voltage /= su8_ad_count;
						//输出18V-32V
	                    if (su16_load_voltage > THRESHOLD_V(18.0) && su16_load_voltage < THRESHOLD_V(32.0))	
	                    {
	                        flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SHORT), CLEAR, ACTION_BATOFF);
	                    }
	                    su16_load_voltage = 0;
	                    su8_ad_count = 0;
	                }
	            }
			}
			
			if (IS_TIMER_END(TIMER_LOAD_RECOVERY))					//针对过流保护时触发，做成打嗝输出，开关时间参数和系统硬件相关
			{
				if (gst_load.current <= LOAD_CURRENT_SIGNAL_RECOVERY)
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER), CLEAR, STATE);
					//gst_load.count = 0;
				}
				if (gst_load.current <= LOAD_CURRENT_OVER1)
				{
					flag_operation(&(gst_load.LOAD_FLAG_CURRENT_OVER), CLEAR, STATE|ACTION_MAINOFF|ACTION_BATOFF);
					//gst_load.count = 0;
				}
				CLEAR_TIMER(TIMER_LOAD_RECOVERY);
				count_flag = 0;
			}
			k = 0;
			gu8_com_data_init_end |= 0x20;
			gu8_soft_wdg_clear_flag |= 0x20;
		}
	}
}



/**
功能：充电器电压检查
返回：无
*/
void Check_Charger_Voltage(void)
{
	static unsigned char k = 0, su8_check_flag = 0, su8_check_vdd_time = 0;
	static uint16_t charger_vdd_voltage_ad_value = 0, charger_voltage_ad_value = 0;

	if (gu8_detect_count == 2 && (gu16_detect_done & 0x0040) == 0 && (gu16_detect_done & 0x0080))		//采样DEAL_WITH_CYCLE = 10次
	{
		DISABLE_INTERRUPTS();
		charger_vdd_voltage_ad_value += getADC0(VDD);
		charger_voltage_ad_value += getADC0(V_CHARGER);
		ENABLE_INTERRUPTS();
		k++;
		gu16_detect_done &= (uint16_t)(~0x0080);
		if (k >= DEAL_WITH_CYCLE)					//140us
		{
			//扩大100倍，精度0.01V
			gst_charger.vdd_voltage = (uint16_t)(charger_vdd_voltage_ad_value * 1.0 / (k) 
								  				 * ADC_BASE_VOLTAGE * ADC_CHARGER_V_TIMES / ADC_BASE * 100  + 0.5);
			charger_vdd_voltage_ad_value = 0;

			//扩大100倍，精度0.01V
			gst_charger.voltage = (uint16_t)(charger_voltage_ad_value * 1.0 / (k) 
								 			 * ADC_BASE_VOLTAGE * ADC_CHARGER_V_TIMES / ADC_BASE * 100  + 0.5);
			charger_voltage_ad_value = 0;

			//这里在电池充饱的时候再检测，充电过程中在电池电压检测功能部分检测
			if ((gst_battery.chg_current < BATTERY_CHARGING_FULL_CURRENT_LEAD_ACID))		
			{
				if (gst_charger.vdd_voltage < VDD_VOLTAGE_LOW || gst_charger.vdd_voltage > VDD_VOLTAGE_OVER)
				{
					if (gst_charger.vdd_voltage < VDD_VOLTAGE_LOW)		//低于15V
					{
						//bit0-CHARGER_FLAG_VEE_LOW
						if (su8_check_flag != 1)									//第一次切换到此状态，定时10min检测确认，目前发现温度补偿过程中触发充电器保护
						{
							SET_TIMER_MS(TIMER_CHECK_CHARGER_VOLTAGE, 60000); 		//60S
							su8_check_flag = 1;
							su8_check_vdd_time = 0;
						}
						
						if (IS_TIMER_END(TIMER_CHECK_CHARGER_VOLTAGE))	
						{
							su8_check_vdd_time++;
							if (su8_check_vdd_time >= 10)
							{
								//不关定时器，等待下一次运行到此时重新触发定时。后续每次9分钟
								su8_check_vdd_time = 0;
								flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), SET, STATE);			
								flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_CHARGEROFF);
							}
							else
							{
								SET_TIMER_MS(TIMER_CHECK_CHARGER_VOLTAGE, 60000);	//60S
							}
						}
						
					}
					else if (gst_charger.vdd_voltage > VDD_VOLTAGE_OVER)	//高于34V
					{
						//bit1-CHARGER_FLAG_VEE_OVER
						su8_check_flag = 0;
						su8_check_vdd_time = 0;
						CLEAR_TIMER(TIMER_CHECK_CHARGER_VOLTAGE);
						flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), SET, STATE|ACTION_CHARGEROFF);	
						flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), CLEAR, STATE);
					}
				}
				else if (gst_charger.vdd_voltage > VDD_VOLTAGE_LOW_RECOVERY 
						&& gst_charger.vdd_voltage < VDD_VOLTAGE_OVER_RECOVERY)
				{
					su8_check_flag = 0;
					su8_check_vdd_time = 0;
					CLEAR_TIMER(TIMER_CHECK_CHARGER_VOLTAGE);
					flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), CLEAR, STATE|ACTION_CHARGEROFF);
					flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_CHARGEROFF);
				}
			}
			else
			{
				su8_check_flag = 0;
				CLEAR_TIMER(TIMER_CHECK_CHARGER_VOLTAGE);

				su8_check_vdd_time = 0;													
				flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), CLEAR, STATE|ACTION_CHARGEROFF);
				flag_operation(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), CLEAR, STATE|ACTION_CHARGEROFF);
			}
			k = 0;
			gu8_com_data_init_end |= 0x40;
			gu8_soft_wdg_clear_flag |= 0x40;
		}
	}
}



/**
功能：充电任务
返回：无
//Vpin = (5*2)/(R+2)
//R = 5*2/Vpin - 2
//  = 5*2/(res*5/1024) - 2
//  = 5*2 * 1024 / 5 /res - 2
//  = 2*1024/res - 2
*/
void Charging_Work(void)
{
	static uint8_t k = 0;
	static uint8_t first_up_flag = YES, time_count = 0, change_flag = YES;
	float charger_temp = 0;
	static uint16_t su16_bat_temp1_ad_value = 0;
#if CHECK_BAT_3_CELL_EN > 0
	static uint16_t su16_bat_temp2_ad_value = 0;
#endif
#if CHECK_CHARGER_DAC_EN > 0
	static float old_charger_temp = 0;
	static uint8_t trend = 0;
#endif
	uint16_t u16_temp1_ad_value = 0;

	if (gu8_detect_count == 3 && (gu16_detect_done & 0x0100))		//采样DEAL_WITH_CYCLE = 10次
	{
		DISABLE_INTERRUPTS();
		su16_bat_temp1_ad_value = getADC1(RT_1);
#if CHECK_BAT_3_CELL_EN > 0
		su16_bat_temp2_ad_value = getADC1(RT_2);
#endif
		ENABLE_INTERRUPTS();
		su16_bat_temp1_ad_value = kalman_filter_For_Temp(su16_bat_temp1_ad_value);

		k++;
		gu16_detect_done &= ~(0x0100);
		
		if (k >= DEAL_WITH_CYCLE)			//468us执行完
		{
#if CHECK_BAT_3_CELL_EN > 0
			u16_temp1_ad_value = ((su16_bat_temp1_ad_value > su16_bat_temp2_ad_value) ? su16_bat_temp1_ad_value : su16_bat_temp2_ad_value);
#else
			u16_temp1_ad_value = su16_bat_temp1_ad_value;
#endif
			charger_temp = Calculate_Thermistor_Value(u16_temp1_ad_value*1.0);

			gst_battery.temp1 = (int16_t)charger_temp;
#if CHECK_BAT_3_CELL_EN > 0
			su16_bat_temp2_ad_value = 0;
#endif
			//备电没有丢失，否则清除并不再更新过温标志位
			if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
			{
				if (gst_battery.temp1 >= TEMPRATURE_SHORT)		//当NTC温度大于60°时候电池过温关闭充电器
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_BAT_OVER_TEMP), SET, STATE|ACTION_CHARGEROFF);
				}
				else if (gst_battery.temp1 < TEMPRATURE_RECOVER)
				{
					flag_operation(&(gst_battery.BATTERY_FLAG_BAT_OVER_TEMP), CLEAR, STATE|ACTION_CHARGEROFF);
				}	
			}
#if CHECK_CHARGER_DAC_EN > 0
			if (gst_load.current >= 280)						//放电电流较大，电源发热量大，根据测试数据，直接减10度补偿
			{
				charger_temp -= 10;
			}
			else
			{
				if ((charger_temp-old_charger_temp) > 2)
				{
					old_charger_temp = charger_temp;
					trend = UP;
				}
				else if ((old_charger_temp-charger_temp) > 2)
				{
					old_charger_temp = charger_temp;
					trend = DOWN;
				}

				if (trend == UP)
				{
					if (charger_temp >= 5.0)
					{
						charger_temp += 1;
					}
					else
					{
						charger_temp += 3;
					}
				}
				else if (trend == DOWN)
				{
					if (charger_temp <= 35.0)
					{
						charger_temp += 1;
					}
					else
					{
						charger_temp += 3;
					}
				}
			}

			//暂不处理低温情况，即低温时一直开着充电器
			if (charger_temp < TEMPRATURE_MIN)  				//其实全范围温度补偿后的范围是-10°C-50°C
			{
				charger_temp = TEMPRATURE_MIN;
			}
			else if (charger_temp > TEMPRATURE_MAX)
			{
				charger_temp = TEMPRATURE_MAX;
			}
			
			gst_battery.temp_adjust = (int16_t)(charger_temp);

			//开机后等待检测温度值收敛完成后才进入温度补偿模式
			if (first_up_flag == YES)
			{
				//第一次调节
				if (change_flag == YES)
				{
					change_flag = NO;
					time_count = 0;
				}
				
				time_count++;
				if (time_count >= 5)	//5*700ms=3.5s
				{
					time_count = 0;
					first_up_flag = NO;	//延时结束，进入温度补偿模式
					change_flag = YES;
				}
				
			}
			else
			{				
				time_count++;
				if (time_count >= 2)	//2*700ms=1.4 调节一次DAC
				{
					time_count = 0;
					set_dacu_volatage_of_temperature(charger_temp);
				}
			}
#endif
		
			k = 0;
			gu8_com_data_init_end |= 0x80;
			gu8_soft_wdg_clear_flag |= 0x80;
		}
	}
}





/**
功能：电池充满检测
返回：无
*/
void Check_Battery_Full(void)
{
    static uint8_t k = 0, su8_check_flag = 0;
	if (gu8_detect_count == 5 && (gu16_detect_done & 0x0200))		//采样DEAL_WITH_CYCLE = 10次
	{
        k++;
		gu16_detect_done &= ~(0x0200);
		
        if (k >= DEAL_WITH_CYCLE)
        {
    		//充电开关打开，充电电流小于0.26A可认为充满
            if ((CHARGER_IO_STATE() != LOW) && (gst_battery.chg_current < BATTERY_CHARGING_FULL_CURRENT_LEAD_ACID))	
            {
            	if (su8_check_flag != 1)
            	{
					//第一次出现此条件等待3S再检测判断，也用做延时判断
					SET_TIMER_MS(TIMER_CHECK_BAT_FULL, TIMER_VCH_DELAY_MS);		//定时3S
					su8_check_flag = 1;
				}
            	
				if (IS_TIMER_END(TIMER_CHECK_BAT_FULL))
				{
					//电池已充满,总压大于26.0V，应用中暂不考虑中点电压，电池电压为判断依据2
					if (gst_battery.voltage > BATTERY_FULL_CHECK_VOLTAGE)		
	                {
	                    flag_operation(&(gst_battery.BATTERY_FLAG_FULL), SET, STATE);
						flag_operation(&(gst_charger.CHARGER_FLAG_STATUS), SET, STATE);	 //充电完成
	                }
					else
					{
						flag_operation(&(gst_battery.BATTERY_FLAG_FULL), CLEAR, STATE);
					}
				}
            }
			//充电器非备电丢失情况下关闭或充电电流恢复则清除充饱标志位，备电丢失时单独清此标志位
            else if ((CHARGER_IO_STATE() == LOW 
					   && flag_read(&(gst_battery.BATTERY_FLAG_RES_OVER), ACTION_CHARGEROFF) == CLEAR 
					   && flag_read(&(gst_battery.BATTERY_FLAG_LOST), ACTION_CHARGEROFF) == CLEAR) 
					  || gst_battery.chg_current > BATTERY_CHARGING_RECOVERY_CURRENT_LEAD_ACID)	
            {		
            	if (su8_check_flag != 2)
            	{
					//第一次出现此条件等待3S再检测判断，也用做延时判断
					SET_TIMER_MS(TIMER_CHECK_BAT_FULL, TIMER_VCH_DELAY_MS);		//定时3S
					su8_check_flag = 2;
				}
				
            	if (IS_TIMER_END(TIMER_CHECK_BAT_FULL))
            	{
	            	flag_operation(&(gst_battery.BATTERY_FLAG_FULL), CLEAR, STATE);
            	}
            }
        	
            k = 0;
        }
	}
}


/**
功能：电池内阻检测
返回：无
*/
void Check_Battery_Resistance(void)
{
	static uint8_t count = 0;
	uint16_t ad = 0, bat_ad_value = 0, vdd_ad_value = 0;
	float voltage = 0;
	
	//电池充满
	if (flag_read(&(gst_battery.BATTERY_FLAG_FULL), STATE) == SET)			
	{
		if (gu16_battery_res_timer < gu8_check_battery_resistance_time)
		{
			if (!IS_TIMER_STARTED(TIMER_CHECK_BATTERY_RESISTANCE))
			{
				//默认定时60S,工装测试模式时时间大于60S则不变,小于则改变
				SET_TIMER_MS(TIMER_CHECK_BATTERY_RESISTANCE, gu16_check_battery_resistance_ms);	
			}
			
			if (IS_TIMER_END(TIMER_CHECK_BATTERY_RESISTANCE))
			{
				gu16_battery_res_timer++;
				if (gu16_battery_res_timer >= gu8_check_battery_resistance_time)				//总定时时间到
				{
					DISABLE_INTERRUPTS();
					bat_ad_value = getADC0(BAT);
					vdd_ad_value = getADC0(VDD);
					ENABLE_INTERRUPTS();
					if (abs(vdd_ad_value-bat_ad_value) < 28)									//差值小于1.5V, 1.5/11*1024/5
					{
						if (gu8_detect_battery_resistance_flag == NO && gu8_detect_bat_lost_flag == NO)
						{
							gu8_detect_battery_resistance_flag = YES;								
							CHARGER_OFF();															//关闭充电器
							flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), SET, ACTION_CHARGEROFF);	
							BAT_LOSS_D_ON();
							SET_TIMER_MS(TIMER_CHECK_BATTERY_RESISTANCE, 20);						//重新定时20ms
						}
						else if (gu8_detect_bat_lost_flag == YES)									//正在检测备电丢失
						{
							gu8_detect_battery_resistance_flag = NO;	
							gu16_battery_res_timer = gu8_check_battery_resistance_time - 1;
							SET_TIMER_MS(TIMER_CHECK_BATTERY_RESISTANCE, 3000);						//重新定时3s
						}
					}
					else
					{
						gu16_battery_res_timer = gu8_check_battery_resistance_time - 1;
						SET_TIMER_MS(TIMER_CHECK_BATTERY_RESISTANCE, gu16_check_battery_resistance_ms);	//重新定时
					}
				}
				else
				{
					SET_TIMER_MS(TIMER_CHECK_BATTERY_RESISTANCE, gu16_check_battery_resistance_ms);
				}
			}
		}
		else 						//内阻检测时间到
		{
			if (IS_TIMER_END(TIMER_CHECK_BATTERY_RESISTANCE))
			{
				BAT_LOSS_D_OFF();
				DELAY_US(380);   	//这里延长是根据实测延长来看,以及采样次数也是根据实际情况来看的，可以肯定有2200电容后延迟更久
				for (int i=0; i<5; i++)
				{
					DISABLE_INTERRUPTS();
					ad += getADC0(BR_T);
					ENABLE_INTERRUPTS();
				}
				DISABLE_INTERRUPTS();
				if (getADC0(BAT) > THRESHOLD_V(26.0))	//VBAT > 26.0V
				{
					ENABLE_INTERRUPTS();
					voltage = (float)(ad * 1.0 / 5);
					//原型Vpin/4/6.1/33*43/0.057=R,下面的倍数是仿真结合实测得到的，0.057是实测到4.28V/75Ω
					//1.57是仿真得到的有电容和没有电容的差异。
					float res = (float)(voltage * ADC_BASE_VOLTAGE / ADC_BASE / 3.1 / 6.1 / 33.0 * 43.0 / 0.057 + 0.05);
					gst_battery.resistance = (uint16_t)(res * 100);//值扩大100倍，单位欧姆
					if (gst_battery.resistance > BATTERY_RESISTANCE_OVER)
					{
						count++;
						if (count >= 5)
						{
							count = 0;
							flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), SET, STATE);
						}
					}	
					else if (gst_battery.resistance < BATTERY_RESISTANCE_OVER_RECOVERY)
					{
						count = 0;
						flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), CLEAR, STATE);
					}
				}
				ENABLE_INTERRUPTS();
				//一定是采样完成后再开充电器，避免了充电器的影响
				flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), CLEAR, ACTION_CHARGEROFF);
				gu16_battery_res_timer = 0;//重置定时器
				gu8_detect_battery_resistance_flag = NO;
				CLEAR_TIMER(TIMER_CHECK_BATTERY_RESISTANCE);
				if (gu8_get_real_vbat_flag == YES)
				{
					BAT_LOSS_D_ON();
				}
			}
		}
	}
	//电池未充满
	else if (flag_read(&(gst_battery.BATTERY_FLAG_FULL), STATE) == CLEAR)		
	{
		if (IS_TIMER_STARTED(TIMER_CHECK_BATTERY_RESISTANCE))
		{
			CLEAR_TIMER(TIMER_CHECK_BATTERY_RESISTANCE);
		}
		flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), CLEAR, STATE);
		if (flag_read(&(gst_battery.BATTERY_FLAG_RES_OVER), ACTION_CHARGEROFF) == SET)
		{
			flag_operation(&(gst_battery.BATTERY_FLAG_RES_OVER), CLEAR, ACTION_CHARGEROFF);
		}
		if (BAT_LOSS_IO_STATE() != LOW
			&& gu8_detect_battery_resistance_flag == YES
			&& gu8_get_real_vbat_flag == NO)
		{
			BAT_LOSS_D_OFF();
		}
		gu16_battery_res_timer = 0;
		gu8_detect_battery_resistance_flag = NO;
		if (gst_battery.resistance != 0)
		{
			gst_battery.resistance = 0;
		}
	}
	
}


/**
功能：充电端口（电池端口）检测保护
返回：无
*/
void Charger_Port_Short_Protect(void)
{	
	uint16_t ad_value = 0;

	DISABLE_INTERRUPTS();
	ad_value = getADC0(BAT);
	ENABLE_INTERRUPTS();
	//灵敏度很高，结合实际充电管子考虑延时情况
	//THRESHOLD_V(0.17)
	if (ad_value <= 3							
		&& gu8_detect_battery_resistance_flag == NO
		&& gu8_detect_bat_lost_flag == NO)			
	{
		flag_operation(&(gst_battery.BATTERY_FLAG_PORT_SHORT), SET, ACTION_CHARGEROFF);
		CHARGER_OFF();
		flag_operation(&(gst_charger.CHARGER_FLAG_STATUS), SET, STATE);
	}

	//用于只有备电时出现突然插拔备电时可以及时失能输出
	//THRESHOLD_VBAT(10)
	if (ad_value <= 186 && gu8_output_power_flag == BAT_OUT)			
	{
		flag_operation(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), SET, ACTION_BATOFF);
		BATOFF_OFF();
	}
}

/**
功能：AC掉电及时关掉充电器
返回：无
*/
void AC_Down_Charger_Close(void)
{	
	static uint8_t down_count = 0;

	if (gst_acpower.ad_value < THRESHOLD_V_CHARGER_OFF_80V)			//灵敏度很高，结合实际考虑延时情况
	{
		down_count++;
		if (down_count >= 5)
		{
			down_count = 0;
			flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW_FAST), SET, ACTION_CHARGEROFF);
			CHARGER_OFF();
			flag_operation(&(gst_charger.CHARGER_FLAG_STATUS), SET, STATE);
		}
	}
	else
	{
		down_count = 0;
		flag_operation(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW_FAST), CLEAR, ACTION_CHARGEROFF);
	}
}


void _16bit28byte(uint8_t *buff, uint16_t data)
{
    buff[0] = data>>8;
    buff[1] = data & 0xff;
    return;
}

/**
功能：发送运行信息
返回：无
*/
static void Send_Info(uint8_t gu8_EmerFlag)
{
    unsigned char buf[48] = {0};
    uint8_t *p = &buf[0];
    uint8_t len = 0;

    //值放大十倍上传
    _16bit28byte(p, gst_acpower.voltage*10);   								// 1#  交流电压 
    p += 2;
    _16bit28byte(p, gst_load.voltage/10);     							 	// 2#  负载电压 
    p += 2;
	_16bit28byte(p, gst_load.current/10);    								// 3#  负载电流 
    p += 2;
    _16bit28byte(p, gst_battery.voltage/10);  								// 4#  电池总压 
    p += 2; 
	if (gst_battery.voltage < gst_battery.m1_voltage)
		_16bit28byte(p, 0x00);
	else
		_16bit28byte(p, (gst_battery.voltage-gst_battery.m1_voltage)/10);  	// 5#  电池2电压 
    p += 2; 
	_16bit28byte(p, gst_battery.m1_voltage/10);  							// 6#  电池1电压 第一节
    p += 2; 
	_16bit28byte(p, 0x8033);  												// 7#  电池温度1 
    p += 2; 
    _16bit28byte(p, (uint16_t)gst_battery.temp1);							// 5#  电池温度2 
    p += 2; 


	_16bit28byte(p, gst_battery.resistance/10);   							// 6#  电池内阻
	p += 2;
	_16bit28byte(p, gst_battery.chg_current/10);   							// 7#  充电电流
	p += 2;
	_16bit28byte(p, gst_charger.voltage/10);   								// 8#  充电电压 
    p += 2;
    _16bit28byte(p, gst_charger.vdd_voltage/10);  							// 9#  充电Vdd电压
	p += 2;
	
																																
		
	
	*p++ |= 				((gst_load.POWER_FLAG_OUTPUT_STATE & 0x01)<<7) +				//bit7-电源输出就绪								
							((gst_battery.BATTERY_FLAG_BAT_OVER_TEMP & 0x01)<<6) +			//bit6-电池过温 						
							((gst_battery.BATTERY_FLAG_VOLTAGE_LOW & 0x01)<<5) +			//bit5-电池欠压 	<21V					
							((gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW & 0x01)<<4) +			//bit4-AC欠压 <95V							
							((gst_charger.CHARGER_FLAG_STATUS & 0x01)<<3) + 				//bit3-充电状态 								
							((gst_battery.BATTERY_FLAG_LOST & 0x01)<<2) +					//bit2-电池丢失 								
							((gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE & 0x01)<<1) +			//bit1-电池电压过低	<23V						
							((gu8_output_power_flag & 0x01)<<0); 							//bit0-主备电状态指示								
	
	*p++ |=					((gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER & 0x02)<<6) + 			//bit7-AC过压 >270V					
							((gst_charger.VDD_FLAG_VOLTAGE_OVER & 0x01)<<6) +				//bit6-VDD过压
							((gst_battery.BATTERY_FLAG_PORT_SHORT & 0x01)<<5) + 			//bit5-电池充电端口短路								
							((gst_charger.VDD_FLAG_VOLTAGE_LOW & 0x01)<<4) +				//bit4-VDD欠压
																			 				//bit3-预留				
							((gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW & 0x02)<<1) +			//bit2-AC故障--AC<90V						
							((gst_load.LOAD_FLAG_CURRENT_SIGNAL_OVER & 0x01)<<1); 			//bit1-负载过流_12A 							
																															   
	*p++ |=					((gst_battery.BATTERY_FLAG_FULL & 0x01)<<7) +					//bit7-电池充满
							((gst_battery.BATTERY_FLAG_RES_OVER & 0x01)<<6)	+				//bit6-电池内阻过大	
							((gst_load.LOAD_FLAG_CURRENT_OVER & 0x01)<<5) + 				//bit5-负载过流_13.5A 
							((gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE & 0x01)<<4) +		//bit4-电池间电压差异常
							((gst_battery.BATTERY_FLAG_SINGLE_VOLTAGE & 0x01)<<3) +			//bit3-单节电压异常
							((gst_battery.BATTERY_FLAG_VOLTAGE_OVER & 0x01)<<2) +			//bit2-电池过压
							((gst_charger.CHARGER_VOLTAGE_ERROR & 0x02)) +					//bit1-VCHarger过压
							((gst_charger.CHARGER_VOLTAGE_ERROR & 0x01));					//bit0-VCHarger欠压
	
							
	*p++ |= 				gu8_EmerFlag;						

	if (gu8_Isdebug == YES)															//调试输出
	{
		*p++ |= ((gst_load.LOAD_FLAG_CURRENT_SHORT & 0x04)<<5)						//bit7-输出短路
			    + ((CHARGER_IO_STATE()&0x01)<<3) 									//bit3-CHARGER开关状态
			    + ((BATOFF_IO_STATE()&0x01)<<2) 									//bit2-BATOFF开关状态
			    + ((MAINOFF_IO_STATE()&0x01)<<1)									//bit1-MAINOFF开关状态
			    + ((BAT_LOSS_IO_STATE()&0x01)<<0);									//bit0-BAT_LOSS_T开关状态

		*p++ = gs8_calib_ac_value;
		*p++ = (uint16_t)(gf_vmcu*1000)>>8;
		*p++ = (uint16_t)(gf_vmcu*1000) & 0xFF;
		_16bit28byte(p, (uint16_t)gst_battery.temp_adjust); 
		p += 2;
		*p++ = DAC0.DATA;
		#ifdef debug_f
		*p++ = u6_debug_value>>8;
		*p++ = u6_debug_value & 0xFF;
		#endif
	}
	len = (uint8_t)(p - buf);    
	len = protocal_make_cmd_data(gu8_com_type_version, (const uint8_t*)buf, len, gu8_uart_host_send);
    Uart_Host_Write(gu8_uart_host_send, len); 
}


/**
功能：系统状态查询，每次通讯处理流程中调用，依据通讯事件驱动
返回：系统状态
*/
uint32_t Check_Sys_State(void)
{
	uint32_t state = 0;
	static uint16_t su16_Vbat = 0xFF, su16_Vbat1 = 0xFF, su16_Vbat2 = 0xFF, su16_Cbat = 0xFF;
	uint16_t temp = 0;

	if (gu8_com_data_init_end != 0xFF)								//数据没有初始化完成
	{
		
	}
	else
	{
		if (IS_TIMER_STARTED(TIMER_CHECK_SYS_STATE) == NO)
		{
			SET_TIMER_MS(TIMER_CHECK_SYS_STATE, TIMER_DELAY_30S);  	//定时30S
		}

		if (IS_TIMER_END(TIMER_CHECK_SYS_STATE))					//定时完成后执行
	    {
			CLEAR_TIMER(TIMER_CHECK_SYS_STATE);	

			if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
			{				
				if (su16_Cbat != gst_battery.capacity)
				{
					su16_Vbat = gst_battery.capacity;
					state |=(uint32_t) 1<<21;														//bit21-备电电池电量更新
				}
				
				if (su16_Vbat != gst_battery.voltage/10/2)
				{
					su16_Vbat = gst_battery.voltage/20;
					state |= (uint32_t)1<<20;														//bit20-备电电池总压更新
				}
				
				if (gst_battery.voltage >= gst_battery.m1_voltage)
				{
					if (su16_Vbat2 != (gst_battery.voltage-gst_battery.m1_voltage)/10/2)
					{
						su16_Vbat2 = (gst_battery.voltage-gst_battery.m1_voltage)/10/2;
						state |= (uint32_t)1<<23;													//bit23-备电电池2电压更新
					}	
				}
				else
				{
					temp = 0;
					if (su16_Vbat2 != temp)
					{
						su16_Vbat2 = 0;
						state |= (uint32_t)1<<23;													//bit23-备电电池2电压更新
					}
				}
			}
			if (su16_Vbat1 != (gst_battery.m1_voltage/10/2))
			{
				su16_Vbat1 = gst_battery.m1_voltage/10/2;
				state |= (uint32_t)1<<22;														//bit22-备电电池1电压更新
			}
			
	    }

		if (flag_read(&(gst_battery.BATTERY_FLAG_LOST), STATE) == CLEAR)
		{
			if (gst_battery.voltage >= gst_battery.m1_voltage)
			{
				if ((gst_battery.voltage-gst_battery.m1_voltage) < BATTERY_VOLTAGE_SINGLE_LOW)
				{
					state |= (uint32_t)1<<29;													//bit29-备电电池2故障
				}
			}
			else
			{
				state |= (uint32_t)1<<29;														//bit29-备电电池2故障
			}
		}
		if (gst_battery.m1_voltage < BATTERY_VOLTAGE_SINGLE_LOW)								//bit28-备电电池1故障
		{
			state |= (uint32_t)1<<28;
		}

		state |= 	((uint32_t)(gst_load.POWER_FLAG_OUTPUT_STATE & 0x01)<<31) +		//bit31-电源输出正常		
					(((uint32_t)(gst_charger.VDD_FLAG_VOLTAGE_OVER & 0x01)<<30) 	//bit30-VCHarger过压
					| ((uint32_t)(gst_charger.VDD_FLAG_VOLTAGE_LOW & 0x01)<<30)) +	//bit30-VCHarger欠压					
																					//bit27-24-预留
																					//bit19-15-预留
					((gst_battery.BATTERY_FLAG_VOLTAGE_LOW & 0x01)<<14) +			//bit14-电池过放 	<21V
					((gst_battery.BATTERY_FLAG_DIFFERENCE_VOLTAGE & 0x01)<<13) +	//bit13-电池间电压差异常
					((gst_battery.BATTERY_FLAG_RES_OVER & 0x01)<<12)	+			//bit12-电池内阻过大	
					((gst_battery.BATTERY_FLAG_BAT_OVER_TEMP & 0x01)<<11) +			//bit11-电池过温 	
					((gst_battery.BATTERY_FLAG_VOLTAGE_OVER & 0x01)<<10) +			//bit10-电池过压						
					((gst_battery.BATTERY_FLAG_PORT_SHORT & 0x01)<<9) + 			//bit9-电池充电端口短路							
					((gst_battery.BATTERY_FLAG_LOST & 0x01)<<8) +					//bit8-电池丢失 
					((gst_battery.BATTERY_FLAG_SINGLE_VOLTAGE & 0x01)<<7) +			//bit7-单节电压异常
					((gst_battery.BATTERY_FLAG_SIGNAL_VOLTAGE & 0x01)<<6) +			//bit6-电池电压过低	<23V		
					(((~(gst_charger.CHARGER_FLAG_STATUS)) & 0x01)<<5) + 			//bit5-充电状态，原状态翻转后上传，释义改为1为充电中，0为停止充电
					//0<<4 +														//bit4-备电正常，值默认恒为为0
					((gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW & 0x02)<<2) +			//bit3-AC故障--AC<90V 	
					((gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW & 0x01)<<2) +			//bit2-AC欠压 <95V	
					((gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER & 0x02)<<0);			//bit1-AC过压 >270V
					//0<<0;															//bit0-主电正常，值默认恒为为0
	}
	return state;
}

/**
功能：功能执行，负责根据传感器信息执行相关动作
返回：无
*/
void Function_Action(void)
{
	static uint8_t su8_charger_open_flag = 1, su8_main_open_flag = 1;
	if (gu8_detect_count == 4 && gu8_com_data_init_end == 0xFF && (gu16_detect_done & 0x1000)) 		//70ms执行一次
	{
		gu16_detect_done &= (uint16_t)(~0x1000);

	/*******************************************************************************************************************************/
		if	((flag_read(&(gu8_tiger_flag), ACTION_BATOFF) == SET) || 						//按下按键3S手动关机
			(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), ACTION_BATOFF) == SET) || 	//备电放电终止关机
			(flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), ACTION_BATOFF) == SET) ||		//过流保护关机
			(flag_read(&(gst_load.LOAD_FLAG_CURRENT_SHORT), ACTION_BATOFF) == SET))		//短路保护关机	
		{
			BATOFF_OFF();
		}
		else if	((flag_read(&(gu8_tiger_flag), ACTION_BATOFF) == CLEAR) &&
				(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), ACTION_BATOFF) == CLEAR) && 
				(flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), ACTION_BATOFF) == CLEAR) && 
				(flag_read(&(gst_load.LOAD_FLAG_CURRENT_SHORT), ACTION_BATOFF) == CLEAR))
		{
			BATOFF_ON();
		}
	/*******************************************************************************************************************************/
		if	((flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW_FAST), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_battery.BATTERY_FLAG_PORT_SHORT), ACTION_CHARGEROFF) == SET) || 
			(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == SET) || 
			(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_battery.BATTERY_FLAG_BAT_OVER_TEMP), ACTION_CHARGEROFF) == SET) || 
			(flag_read(&(gst_battery.BATTERY_FLAG_LOST), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_battery.BATTERY_FLAG_RES_OVER), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_charger.CHARGER_VOLTAGE_ERROR), ACTION_CHARGEROFF) == SET) || 
			(flag_read(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == SET) ||
			(flag_read(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == SET))
		{
			CHARGER_OFF();
			flag_operation(&(gst_charger.CHARGER_FLAG_STATUS), SET, STATE);		
			su8_charger_open_flag = 1;
			CLEAR_TIMER(TIMER_CHARGER_OPEN_DELAY);
		}
		else if	((flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW_FAST), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_battery.BATTERY_FLAG_PORT_SHORT), ACTION_CHARGEROFF) == CLEAR) && 
				(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == CLEAR) && 
				(flag_read(&(gst_battery.BATTERY_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_battery.BATTERY_FLAG_BAT_OVER_TEMP), ACTION_CHARGEROFF) == CLEAR) && 
				(flag_read(&(gst_battery.BATTERY_FLAG_LOST), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_battery.BATTERY_FLAG_RES_OVER), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_charger.CHARGER_VOLTAGE_ERROR), ACTION_CHARGEROFF) == CLEAR) && 
				(flag_read(&(gst_charger.VDD_FLAG_VOLTAGE_LOW), ACTION_CHARGEROFF) == CLEAR) &&
				(flag_read(&(gst_charger.VDD_FLAG_VOLTAGE_OVER), ACTION_CHARGEROFF) == CLEAR))
		{
			if (su8_charger_open_flag != 0)
			{
				su8_charger_open_flag = 0;
				SET_TIMER_MS(TIMER_CHARGER_OPEN_DELAY, 500);
			}
			if (IS_TIMER_END(TIMER_CHARGER_OPEN_DELAY))
			{
				CHARGER_ON();
			}
		}
	/*******************************************************************************************************************************/
		if	((flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_MAINOFF) == SET) || 
			(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), ACTION_MAINOFF) == SET) || 
			(flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), ACTION_MAINOFF) == SET))
		{
			if (su8_main_open_flag != 0)
			{
				su8_main_open_flag = 0;
				SET_TIMER_MS(TIMER_MAIN_OPEN_DELAY, TIMER_DELAY_100MS);
			}
			if (IS_TIMER_END(TIMER_MAIN_OPEN_DELAY))
			{
				MAINOFF_OFF();
			}
		}
		else if	((flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_LOW), ACTION_MAINOFF) == CLEAR) && 
				(flag_read(&(gst_acpower.ACPOWER_FLAG_VOLTAGE_OVER), ACTION_MAINOFF) == CLEAR) && 
				(flag_read(&(gst_load.LOAD_FLAG_CURRENT_OVER), ACTION_MAINOFF) == CLEAR))
		{
			MAINOFF_ON();
			su8_main_open_flag = 1;
			CLEAR_TIMER(TIMER_MAIN_OPEN_DELAY);
		}
	/*******************************************************************************************************************************/
	}
}


/**
功能：响应主机命令和电源信息上传
返回：无
*/
void Response_Post_And_Send_Info(void)
{
	uint8_t i;
	
	if (gu8_com_data_init_end == 0xFF)						//刚上电等待数据更新完毕后再上传
	{		
        if (((gu8_uarthostRxStatusFlag & 0x08) != 0) && (gu8_com_data_deal_end != 0))  //等待数据处理完成后再执行
        {
        	if (gu8_Isdebug == YES)							//产测模式开启
        	{
        		if (gu8_IsQueryversion == NO)
        		{
            		Send_Info(0x00);
        		}
				else
				{
					gu8_IsQueryversion = NO;
				}
        	}
			//DISABLE_INTERRUPTS();
            gu8_uarthostRxStatusFlag &= ~0x08;				//清除通信标志位
            //ENABLE_INTERRUPTS();
        }
	}
	if ((gu8_uarthostRxStatusFlag & 0x08) != 0)				//接收完一帧数据
    {	
    	for(i=0;i<uart_msg_rec_buffer_num;i++)
    	{
    		if (gst_uart_msg_rec[i].u8is_used == YES)		//有命令待处理
    		{
        		pro_deal_recv_data(gst_uart_msg_rec[i].msg, gst_uart_msg_rec[i].u8len);	//处理数据		
        		//DISABLE_INTERRUPTS();
        		gst_uart_msg_rec[i].u8is_used = NO;
				//ENABLE_INTERRUPTS();
    		}
    	}
        gu8_com_data_deal_end = 1;						//提取完数据
    }		
}





